<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Item;
use App\Model\ItemSku;
use App\Model\Category;
use App\Model\Attribute;
use App\Model\AttributeValue;
use DB;
use Validator;
use App\Model\ItemPackage;


class ItemController extends Controller
{
    public function index()
    {
    	$item=Item::where('status','>=',0)->paginate(15);
    	return view('admin.item.index',compact('item'));
    }

    public function create()
    {
    	$categpry=Category::get();
        $category=GetTree($categpry->toArray(),0,0);
    	return view('admin.item.create',compact('category'));
    }

    public function store(Request $request)
    {   
        $data['cat_id']=$request->input('cat_id');
    	$data['sncode']=$request->input('sncode','1');
        $data['name']=$request->input('name','1');
        $data['stock']=$request->input('stock','1');
        $data['locked']=$request->input('locked','0');
        $data['weight']=$request->input('weight','0');
        $data['market_price']=$request->input('market_price', '0');
        $data['price']=$request->input('price','0');
        $data['keywords']=$request->input('keywords','');
        $data['brief']=$request->input('brief','');
        $data['description']=$request->input('description','');
        $data['is_onsale']=$request->input('is_onsale','1');
        $data['is_alone_sale']=$request->input('is_alone_sale','1');
        $data['is_package']=$request->input('is_package','0');
        $data['cover']=$request->file('cover','');
        
        $sku['skuidstr']=$request->input('skuidstr','');
        $sku['skunamestr']=$request->input('skunamestr','');
        $sku['skuprice']=$request->input('skuprice','');
        $sku['skustock']=$request->input('skustock','');

        
        
        DB::beginTransaction();
        try {
            $request->flash();
            $this->Validator($data);
            //图片上传存储
            $cover=$data['cover'];
            $data['cover']="";
            $item=Item::create($data);
            $pre=pathinfo($cover->getClientOriginalName(),PATHINFO_EXTENSION);
            $filename=md5('goods'.$item->id).".".$pre;
            $url="/upload/".$cover->storeAs('/goods/'.date('Ym',time()),$filename);
            $item->cover=$url;
            $item->save();

            //sku
            if($sku){
                foreach ($sku['skuidstr'] as $k => $v) {
                    $info['sku']=$v;
                    $info['name']=$sku['skunamestr'][$k];
                    $info['price']=$sku['skuprice'][$k];
                    $info['stock']=$sku['skustock'][$k];
                    $info['item_id']=$item->id;
                    ItemSku::create($info);
                }
            }
            
        } catch (\Exception $e) {
            DB::rollback();
            echo $e->getMessage();exit;
            //return redirect()->back();
        }
        DB::commit();
    	return redirect(route('admin.item.index'));
    }


    public function edit(Request $request)
    {   
        $id=$request->id;
    	$item=Item::with('sku')->with('package')->find($id);

        $categpry=Category::get();
        $category=GetTree($categpry->toArray(),0,0);
        $a=$item->toArray();
    	return view('admin.item.edit',compact('item','category','a'));
    }


    public function update(Request $request)
    {   
        $id=$request->input('id');
    	$data['cat_id']=$request->input('cat_id');
        $data['sncode']=$request->input('sncode','1');
        $data['name']=$request->input('name','1');
        $data['stock']=$request->input('stock','1');
        $data['locked']=$request->input('locked','0');
        $data['weight']=$request->input('weight','0');
        $data['market_price']=$request->input('market_price', '0');
        $data['price']=$request->input('price','0');
        $data['keywords']=$request->input('keywords','');
        $data['brief']=$request->input('brief','');
        $data['description']=$request->input('description','');
        $data['is_onsale']=$request->input('is_onsale','1');
        $data['is_alone_sale']=$request->input('is_alone_sale','1');
        $data['is_package']=$request->input('is_package','0');
        $data['cover']=$request->file('cover','');
        
        $sku['skuid']=$request->input('skuid','');
        $sku['skuidstr']=$request->input('skuidstr','');
        $sku['skunamestr']=$request->input('skunamestr','');
        $sku['skuprice']=$request->input('skuprice','');
        $sku['skustock']=$request->input('skustock','');
        
        $package=$request->input('package','');
        
        DB::beginTransaction();
        try {
            $request->flash();
            $item=Item::where('id',$id)->update($data);
            //图片上传存储
            if($data['cover']){

                $cover=$data['cover'];
                $data['cover']="";
                $pre=pathinfo($cover->getClientOriginalName(),PATHINFO_EXTENSION);
                $filename=md5('goods'.$id).".".$pre;
                $url="/upload/".$cover->storeAs('/goods/'.date('Ym',time()),$filename);
                $item->cover=$url;
                $item->save();
            }
            

            //sku
            if($sku){
                foreach ($sku['skuid'] as $k => $v) {
                    $info['sku']=$sku['skuidstr'][$k];
                    $info['name']=$sku['skunamestr'][$k];
                    $info['price']=$sku['skuprice'][$k];
                    $info['stock']=$sku['skustock'][$k];
                    $info['item_id']=$id;
                    ItemSku::where('id',$v)->update($info);
                }
            }
           
            if($data['is_package']){
                foreach ($package as $k => $v) {
                     $p=explode("|",$v);
                     $pak['item_id']=$id;
                     $pak['sku_id']=$p[0];
                     $pak['sku']=$p[1];
                     $pak['package_itemid']=$p[2];
                     $pak['number']=$p[3];
                    
                    if(ItemPackage::where('item_id',$id)->where('sku_id',$pak['sku_id'])->first()){
                        
                        ItemPackage::where('item_id',$id)->where('sku_id',$pak['sku_id'])->update($pak);
                    }else{
                        
                        ItemPackage::create($pak);
                    }
                }
            }
            
        } catch (\Exception $e) {
            DB::rollback();
            echo $e->getMessage();exit;
            //return redirect()->back();
        }
        DB::commit();
        return redirect(route('admin.item.index'));
    



    	
    }

    public function destroy($id)
    {
    	
        Item::where('id',$id)->update(['status'=>'-1']);
        return parent::success('success',route('admin.item.index'));
    	
    }

    public function publish($id)
    {
        
        Item::where('id',$id)->update(['status'=>'1']);
        return parent::success('success',route('admin.item.index'));
        
    }

    public function unpublish($id)
    {
        
        Item::where('id',$id)->update(['status'=>'0']);
        return parent::success('success',route('admin.item.index'));
        
    }

    public function getAttribute(Request $request)
    {   

        $attr_id=$request->attr_id;
        $attr_id=explode(',', $attr_id);
        
        $attribute=Attribute::whereIn('id',$attr_id)->with('val')->get()->toArray();
        foreach ($attribute as $k => $v) {
            foreach ($v['val'] as $k1 => $v1) {
                $v['val'][$k1]['type']=$v['name'];
            }
            $data[]=$v['val'];
        }
        
        $result=$this->dikar($data);
       
       
        return parent::success('success',$result);
    }

    public function getAttributeName(Request $request)
    {   $cat_id=$request->cat_id;
        $attribute=Attribute::where('cat_id',$cat_id)->get()->toArray();
        return parent::success('success',$attribute);
    }

    public function dikar($sets){
        // 保存结果
        
        $result = array();
        $resultType = array();
        $resultSku = array();
        if(count($sets)>1){
            // 循环遍历集合数据
            for($i=0,$count=count($sets); $i<$count-1; $i++){

                // 初始化
                if($i==0){
                    $result = $sets[$i];
                    $resultType = $sets[$i];
                    $resultSku = $sets[$i];
                }

                // 保存临时数据
                $tmp = array();
                $type = array();
                $sku = array();
                
                // 结果与下一个集合计算笛卡尔积
                foreach($result as $res){
                   
                        foreach($sets[$i+1] as $set){
                            if(isset($res['value'])){
                                
                                $tmp[] = $res['value'].",".$set['value'];
                               
                            }else{
                                
                                $tmp[] = $res.",".$set['value'];  
                            }
                        }
                  
                    
                }

                foreach($resultType as $res){

                    foreach($sets[$i+1] as $set){

                        if(isset($res['value'])){
                            
                            $type[]= $res['type'].",".$set['type'];
                        }else{
                            $type[]= $res.",".$set['type'];   
                        }

                    }
                }

                foreach($resultSku as $res){

                    foreach($sets[$i+1] as $set){
                        if(isset($res['value'])){
                            
                            
                            $sku[]= $res['attr_id'].":".$res['id'].";".$set['attr_id'].":".$set['id'];
                            
                        }else{
                            
                            $sku[]= $res.";".$set['attr_id'].":".$set['id'];
                        }
                    }
                }

                // 将笛卡尔积写入结果
                $result = $tmp;
                $resultType = $type;
                $resultSku = $sku;
                
            }
        }else{

           foreach ($sets[0] as $k => $v) {
            
              $result[]=$v['value'];
              $resultType[]=$v['type'];
              $resultSku[]=$v['attr_id'].":".$v['id'];
           }
        }
        $data['tmp']=$result;
        $data['type']=$resultType;
        $data['sku']=$resultSku;
        
        return $data;
    }

    public function Validator(array $data)
    {   
        $validator = Validator::make($data, [
            'sncode'      => 'required',
            'name'      => 'required',
            'stock'      => 'required',
            'locked'      => 'required',
            'market_price'      => 'required',
            'price'      => 'required',
            'keywords'      => 'required',
            'brief'      => 'required',
            'description'      => 'required|string', 
            'cover'      => 'required|file', 
            
            
        ]);
        if ( $validator->fails()){
            $error = $validator->errors()->first();
            throw new \Exception($error,1);
        }
    }
}
